<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-tool-bar">
        <Toolbar
          :items="store.pageData.btnList"
          @add="addHandler"
          @del="deleteHandler"
          @select="selectHandler"
          @export="exportExcel"
          @import="importHandler"
          @excel="downloadHandler"
        ></Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      :ok-loading="pageData.pageLoading"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <!-- <a-form-item
            label-col-flex="80px"
            label="编码"
            field="colorCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              class="bacClass"
              placeholder=""
              @blur="inputBlur"
              v-model="dataForm.colorCode"
            />
          </a-form-item> -->
          <a-form-item
            label-col-flex="80px"
            label="色称"
            field="colorName"
            :rules="[{ required: true, message: '色称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.colorName" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="色号"
            field="colorNumber"
            :rules="[{ required: true, message: '色号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.colorNumber" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="是否停用" field="obsoleteState">
            <a-switch
              checked-color="#F53F3F"
              unchecked-color="#14C9C9"
              v-model="dataForm.obsoleteState"
              :checked-value="1"
              :unchecked-value="0"
              style="width: 65px"
            >
              <template #checked> 停用</template>
              <template #unchecked> 启用</template>
            </a-switch>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <!-- <a-input v-model="dataForm.remark" /> -->
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { addListener } from 'process'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import { useColorInformationStore } from '@/store/product/colorInformation'
  import { storeToRefs } from 'pinia'
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import 'ag-grid-community/styles/ag-grid.css'
  import 'ag-grid-community/styles/ag-theme-alpine.css'
  import { exportStyleExcel } from '@/api/Export2StyleExcel'
  import useAgGridFilterSelector from '@/utils/aggridFilterAllSelect'

  interface MaterialGradeInfo {
    id: any
    colorName: string | undefined
    remark: string | undefined
    deleteState: string | undefined
    createName: string | undefined
    createTime: string | undefined
    updateName: string | undefined
    updateTime: string | undefined
    obsoleteState: number | undefined
    colorNumber: string | undefined
    isDeadStatus: any
  }

  export default {
    name: 'ColorInformation',
    setup() {
      const table1Ref = ref<any>(null)
      const store = useColorInformationStore()
      let tc: any[] = store.tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 90
          obj['cellRenderer'] = {
            template: `
            <a-tag class="tagCss" @click="a" v-if="isEdit">修改</a-tag>`,
            setup(props: any) {
              const isEdit = ref(store.pageData.isEdit)
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                isEdit,
                a,
              }
            },
          }
        }
        if (o.slotName === 'obsoleteState') {
          obj['resizable'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 90
          obj['cellRenderer'] = {
            template: `
            <a-space>
              <el-tag type="success" @click="a" v-if="a==0">
                {{ val }}
              </el-tag>
              <el-tag type="info" @click="b" v-if="a==1">
                {{ val }}
              </el-tag>
            </a-space>`,
            setup(props: any) {
              let val = ref()
              if (props.params.data.obsoleteState == 0) {
                val.value = '启用'
              } else {
                val.value = '停用'
              }

              return {
                val,
                a: props.params.data.obsoleteState,
              }
            },
          }
          obj['filterParams'] = {
            valueFormatter: function (params: any) {
              return params.value == '0' ? '启用' : params.value == '1' ? '停用' : ''
            },
          }
        }
        return obj
      })
      tc.unshift({
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      })
      let configTable1 = ref({
        url: 'product/color/getColorPage', //接口路径
        queryData: {
          //接口参数
          deleteState: 0,
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tc,
        fileName: 'colorInformation',
      })
      const aggridFs = useAgGridFilterSelector()
      const { total, page, size, pageData, selectedRowKeys, table, rowKey, tableColumns } =
        storeToRefs(store)

      function PageSize(val: any) {
        store.page = val
        doRefresh()
      }

      function change1(val: any) {
        store.size = val
        doRefresh()
      }

      async function doRefresh() {
        try {
          store.pageData.pageLoading = true
          table1Ref.value.setQuery({
            deleteState: 0,
          })
        } catch (error) {
          console.error(error)
        } finally {
          store.pageData.pageLoading = false
        }
      }

      const dataForm = reactive<MaterialGradeInfo>({
        id: null,
        colorName: '',
        remark: '',
        deleteState: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        obsoleteState: 0,
        colorNumber: '',
        isDeadStatus: 0,
      })

      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }

      const formRef = ref<FormInstance>()

      onMounted(() => {
        // 切换tap到本页面执行的方法
        // emitter.on('ColorInformation', () => {
        //   // selCxAll({});
        // })
      })
      //查询
      const selectHandler = () => {
        store.page = 1
        doRefresh()
      }

      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
        store.pageData.showAdd = true
        store.pageData.sideTitle = '新增色号色称资料'
      }
      //修改 record（本行数据）
      const editHandler = (record: any) => {
        store.pageData.showAdd = true
        dataForm.id = record.id
        dataForm.colorName = record.colorName
        dataForm.remark = record.remark
        // dataForm.colorCode = record.colorCode
        dataForm.colorNumber = record.colorNumber

        dataForm.obsoleteState = record.obsoleteState
        //侧滑栏滑出滑入

        store.pageData.sideTitle = '修改色号色称资料'
      }

      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            store.pageData.pageLoading = true
            if (store.pageData.sideTitle === '新增色号色称资料') {
              //添加
              post({
                url: 'product/color/addColor',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()

                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                    store.pageData.showAdd = false
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  store.pageData.pageLoading = false
                })
            } else if (store.pageData.sideTitle === '修改色号色称资料') {
              //修改
              post({
                url: 'product/color/updateColor',
                data: [dataForm],
              })
                .then(({ data, code, message }: any) => {
                  if (code === 200) {
                    formRef.value?.resetFields()
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })

                    doRefresh()
                    store.pageData.showAdd = false
                  } else {
                    Message.error({
                      content: message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  store.pageData.pageLoading = false
                })
            }
          }
        })
      }
      const deleteHandler = () => {
        if (table1Ref.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            store.pageData.pageLoading = true
            post({
              url: 'product/color/delColor',
              data: table1Ref.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  store.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                store.pageData.pageLoading = false
              })
          },
        })
      }

      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      const inputBlur = () => {
        dataForm.colorCode = dataForm.colorCode.toUpperCase()
      }

      //前端导出
      function exportExcel() {
        if (table1Ref.value.getSelectedRows().length === 0) {
          Message.error('请先勾选需导出行数据！')
          return
        }
        const header = [
          '序号',
          '色称',
          '色号',
          '备注',
          '创建人',
          '创建时间',
          '最后修改人',
          '最后修改时间',
        ]
        const filterVal = [
          'colorCode',
          'colorName',
          'colorNumber',
          'remark',
          'createName',
          'createTime',
          'updateName',
          'updateTime',
        ]
        let data = formatJson(filterVal, table1Ref.value.getSelectedRows())
        exportStyleExcel({ header, data, filename: '色号色称资料.xlsx' })
      }

      function formatJson(filterVal, jsonData) {
        return jsonData.map((v) =>
          filterVal.map((j) => {
            if (j == 'status') {
              if (v[j] == 1) {
                return '正常'
              } else {
                return '禁用'
              }
            } else {
              if (v[j]) {
                return v[j]
              } else {
                return ''
              }
            }
          })
        )
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/product/color/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '色号色称资料.xlsx')
            }
          })
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          store.pageData.pageLoading = true
          axios
            .post(baseURL + '/product/color/analyseColorModel', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              store.pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('shsc.cx')) {
        store.pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('shsc.xz')) {
        store.pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('shsc.sc')) {
        store.pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('shsc.dc')) {
        store.pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('shsc.mbxz')) {
        store.pageData.btnList.push('模板下载')
      }
      if (permissionStore.hasPermisson('shsc.dr')) {
        store.pageData.btnList.push('导入')
      }
      if (permissionStore.hasPermisson('shsc.xg')) {
        store.pageData.isEdit = true
      }
      const handleChange = (_data: any) => {
        store.table.dataList = _data
      }
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        //flex: 1
      }
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      return {
        colState,
        store,
        pagingList1,
        localeText1,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        tableColumns,
        table,
        rowKey,
        pageData,
        editHandler,
        selectHandler,
        isChiese,
        inputBlur,
        exportExcel,
        downloadHandler,
        importHandler,
        handleChange,
        gridReady,
        aggridFs,
        table1Ref,
        configTable1,
      }
    },
    components: { Toolbar },
  }
</script>
<style scoped lang="less">
  .toolbar-item {
    cursor: pointer;
  }
</style>
